var locationDetailInfoDialog;
var gotoPage, toUnsafeSummery, checkLine, showDataDetail, textClick;
require(['gaodeMap', 'highcharts', 'grid', 'homePageTools', 'zTreeCheckbox'], function () {
	//TODO
	var safeType = "1",
		funcType = "captainHome",
		dateType="02",
		params = {},
		groupType = "",
		stationMarkers = [],													//车站Marker集合
		tmpLineNames = [],
		carMarkers = [],
//		contentMarks = [],
		//TODO 
		faultMarkers = [],
		unsafeMarkers = [],
		overspeedMarkers = [],
		fuelTypeCode = '0,1,6',
		fuelTypeTot = '030101',
		idxType = '030101',
		map,
		interval = null,
        flag = false,
        treeObj = null,
		dateAr = [];															//日期数组
	var totalCars=0, totalMile=0, totalEnerCons=0, totalOprtDura=0,
		enerConsPer=0, faultCarsCount=0, unsafeDrvCount=0, unsafeBhvCount=0;

    var setting = {
        view : {
            showIcon : true,
            selectedMulti : false,
            fontCss: function (treeId, treeNode) {
                if (treeNode.type === 'LINE') {
                	return 'line-icon';
				}else{
                    return 'org-icon';
				}
            }
        },
        data : {
            key : {
                name : "name"
            },
            simpleData : {
                enable : true,
                idKey : "id",
                pIdKey : "parentId",
                rootPId : 0
            }
        },
        check: {
            enable: true,
            chkStyle: "checkbox",
            chkboxType: { "Y": "s", "N": "ps" }
        },
        callback : {
            onCheck : function(){
                checkLine();
			}
        }
    };


	//加载用户线路资源
	$.ajaxExt({
		url: "/homeCaptain/getCaptainLineInfo.htm"
	}).done(function(data){
		if(data){
            treeObj = $("#leftTree").createTree(setting, data, {search: $('#searchlabel')});
		}
	});
	
	$('#financeTab').grid({
        multiselect: false,
        url: "/homeCaptain/getCaptainFinanceData.htm",
        height : 450,
        width: 1150,
        colModel: [
            {name: "drvId", label: "drvId", hidden: true},
            {name: "carId", label: "carId", hidden: true},
            {name: "lineId", label: "lineId", hidden: true},
            {name: "organId", label: "organId", hidden: true},
            {name: "loLgt", label: "loLgt", hidden: true},
            {name: "loLtt", label: "loLtt", hidden: true},
            {name: "licPltNo", label: "车牌号", align: "center"},
            {name: "lineName", label: "营运线路", align: "center"},
            {name: "drvName", label: "驾驶员 ", align: "center"},
            {name: "organName", label: "所属机构", align: "center"},
            {name: "rcrdTime", label: "时间", align: "center"},
            {name: "locateDetail", label: "具体地点", align: "center",
                formatter: 'operArea',
                formatoptions: [
                    {
                        text: '详细位置',
                        css:'operate operate-location',
                        click: function (data) {
                            showDataDetail(data);
                        }
                    }
                ]
            }
        ]
    });
	
	//设置高度
	function setHeight() {
        var height = $(window).height();
        $("#layoutLeft,#layoutLeft > .layout-right").height(height);
        // $("#lineChkBox").height(height-94);
        $("#leftTree").height(height-94);
        $('#unsafeMapDiv').height(height);
        $('#mapDiv').height(height);
        $('#iCenter').height(height);
    }
	
	window.onresize = setHeight;
	
	checkLine = function(){
		$('#showSelectLines').empty();
		var lineInfo = '';
		var shortLineInfo = '';

        var nodes = treeObj.getCheckedNodes(true);
        if(nodes && nodes.length > 0){
            $.each(nodes, function(index, item){
                if(item.type == 'LINE'){
                    shortLineInfo += '<a>'+item.name+';</a>';
                    lineInfo += '<a>'+item.name+'</a>';
                }
            });
        }

		// $("input[name='lineChk']:checked").each(function(){
		// 	shortLineInfo += '<a>'+$(this).attr('dscVal')+';</a>';
		// 	lineInfo += '<a>'+$(this).attr('dscVal')+'</a>';
		// });
		$('#showSelectLines').html(shortLineInfo);
		$('.all-show').html(lineInfo);
	};
	
	textClick = function(obj){
		$(obj).parent().find('input').click();
	};

    /**
	 * 初始化查询参数
     */
	function initParams(){
		//获取所选线路
		var lineIds = [];
		var lineNames = [];
        var nodes = treeObj.getCheckedNodes(true);
        if(nodes && nodes.length > 0){
            $.each(nodes, function(index, item){
            	if(item.type == 'LINE'){
                    lineIds.push(item.id);
                    lineNames.push(item.name);
                }
            });
		}
		tmpLineNames = lineNames;
		params.lineIds = lineIds;
        params.type = groupType;
		//获取时间类型
		params.dateType = dateType;
		params.timeFrequence = $("#refreshIntev").val();
	}
	
	/**
	 * 加载数据
	 */
	function loadData(type){
		if(type != 'captainHome'){
			clearInterval(interval);
		}
		//清空
		params = {};
		var lineNames = [];
		//TODO
        var nodes = treeObj.getCheckedNodes(true);
        if(nodes && nodes.length > 0){
			$.each(nodes, function(index, item){
                if(item.type == 'LINE'){
                    lineNames.push(item.name);
                }
			});
            if(lineNames && lineNames.length > 0){
                if(type == 'captainHome'){
                    loadCaptainHomeData();
                }else if(type == 'captainSafe'){
                    loadCaptainSafeData();
                }else if(type == 'captainEnergy'){
                    loadCaptainEnergyData();
                }else if(type == 'captainDriver'){
                    loadCaptainDriverData();
                }else if(type == 'captainFinance'){
                    loadCaptainFinanceData();
                }
            }else{
                $.messager.alert("警告","请先选择线路！","info");
            }
        }else{
            $.messager.alert("警告","请先选择线路！","info");
        }
	}

    //TODO==================================================================================================首页部分begin=======================================================================================================================
	/**
	 * 加载车队长首页
	 */
	function loadCaptainHomeData(){
		if(fuelTypeCode != ''){
			params.fuelTypeCode = fuelTypeCode;
			params.fuelTypeTot = fuelTypeTot;
		}
		else{
			params.fuelTypeCode = $('#homeOilType').attr('val');
			params.fuelTypeTot = $('#homeOilType').attr('indexType');
		}
		
		//加载指标
		loadCaptainHomeIndexData();
	}

    /**
	 * 地图中故障信息列表样式
     */
    $(".slide-btn2").click(function(){
        if(flag){
            $(this).addClass("slide-btn2-show");
            $(".fault-box").addClass("fault-box-hide");
        }
        if($(this).hasClass("slide-btn2-show")){
            $(this).removeClass("slide-btn2-show");
            $(".fault-box").removeClass("fault-box-hide");
        }else {
            $(this).addClass("slide-btn2-show");
            $(".fault-box").addClass("fault-box-hide");
        }
        flag=false;
    });
	
	/**
	 * 加载指标
	 */
	function loadCaptainHomeIndexData(){
		getAjaxData("/homeCaptain/getHomeIndex.htm", function(data){
			if(data){
				$("#totalCars").html('<strong>'+data.totalCars+'</strong><span>辆</span>');
				totalCars = data.totalCars;
				$("#carOnLine").html('<strong>'+(data.carOnLine+data.carInMotion)+'</strong><span>辆</span>');
				$("#carInMotion").html('<strong>'+data.carInMotion+'</strong><span>辆</span>');
				$("#onLinePer").html('<strong>'+data.onLinePer+'</strong><span>%</span>');
				var unit1 = 'L', unit2 = 'L/100km';
				if(idxType == '030102'){
					unit1 = 'KWH';
					unit2 = 'KWH/100km';
				}
				
				$("#totalEnerCons").html('<strong>'+data.totalEnerCons+'</strong><span>'+unit1+'</span>');
				$("#energyMomPer").html(data.totalEnerMomPer+"%");
				totalEnerCons = data.totalEnerMomPer;
				$("#totalMile").html('<strong>'+data.totalMile+'</strong><span>KM</span>');
				$("#mileMomPer").html(data.mileMomPer+"%");
				totalMile = data.mileMomPer;
				$("#enerConsPer").html('<strong>'+data.enerConsPer+'</strong><span>'+unit2+'</span>');
				$("#consValMomPer").html(data.enerMomPer+"%");
				enerConsPer = data.enerMomPer;
				$("#totalOprtDura").html('<strong>'+data.totalOprtDura+'</strong><span>小时</span>');
				$("#duraMomPer").html(data.duraMomPer+"%");
				totalOprtDura = data.duraMomPer;
				
				$("#faultCarsCount").html('<strong>'+data.faultCarsCount+'</strong><span>次</span>');
				faultCarsCount = data.faultCarsCount;
				$("#unsafeBhvCount").html('<strong>'+data.unsafeBhvCount+'</strong><span>次</span>');
				unsafeDrvCount = data.unsafeDrvCount;
				$("#unsafeDrvCount").html('<strong>'+data.unsafeDrvCount+'</strong><span>人</span>');
				unsafeBhvCount = data.unsafeBhvCount;
				$("#maintExpire").html('<strong>'+data.maintExpire+'</strong> <span>辆</span>');
				loadCaptainLastHomeIndex();
			}
		});
	}
	
	/**
	 * 加载对比指标指标
	 */
	function loadCaptainLastHomeIndex(){
		getAjaxData("/homeCaptain/getCompareIndex.htm", function(data){
			$(".rise-down").removeClass("down");
			if(data){
				var cmpTotalCars = totalCars - data.totalCars,
				cmpFaultCarsCount = faultCarsCount - data.faultCarsCount,
				cmpUnsafeDrvCount = unsafeDrvCount - data.unsafeDrvCount,
				cmpUnsafeBhvCount = unsafeBhvCount - data.unsafeBhvCount;
				var perVal = convertIndexVal(cmpTotalCars, data.totalCars);
				$("#carMomPer").html(perVal);
				if(cmpTotalCars<0){
					$("#carMomPer").addClass("down");
				}
				if(totalEnerCons<0){
					$("#energyMomPer").addClass("down");
				}
				if(totalMile<0){
					$("#mileMomPer").addClass("down");
				}
				if(enerConsPer<0){
					$("#consValMomPer").addClass("down");
				}
				if(totalOprtDura<0){
					$("#duraMomPer").addClass("down");
				}
				perVal = convertIndexVal(cmpFaultCarsCount, data.faultCarsCount);
				$("#faultMomPer").html(perVal);
				if(cmpFaultCarsCount<0){
					$("#faultMomPer").addClass("down");
				}
				perVal = convertIndexVal(cmpUnsafeDrvCount, data.unsafeDrvCount);
				$("#unsafeDrvMomPer").html(perVal);
				if(cmpUnsafeDrvCount<0){
					$("#unsafeDrvMomPer").addClass("down");
				}
				perVal = convertIndexVal(cmpUnsafeBhvCount, data.unsafeBhvCount);
				$("#unsafeBhvMomPer").html(perVal);
				if(cmpUnsafeBhvCount<0){
					$("#unsafeBhvMomPer").addClass("down");
				}
			}
		});
	}
	
	/**
	 * 得到百分比
	 */
	function convertIndexVal(cmpVal, totalVal){
		var perVal = cmpVal*100/totalVal;
		if(totalVal == 0){
			perVal = '-';
		}
		if(isNaN(perVal))
			perVal = "-";
		else
			perVal = perVal.toFixed(2)+"%";
		return perVal;
	}

    /**
	 * 刷新车辆位置
     */
	function updateMapInfo(){
		var selLines = [];
        var nodes = treeObj.getCheckedNodes(true);
        if(nodes && nodes.length > 0){
            $.each(nodes, function(index, item){
                if(item.type == 'LINE'){
                    selLines.push(item.id);
                }
            });
        }
		// $("input[name='lineChk']:checked").each(function(){
		// 	selLines.push($(this).val());
		// });
		if(selLines.length > 0){
			//TODO
			getLineCarLastPosition();
			getRecentWarnInfo();
			//查询最近十分钟发生的报警
			getLastMiniteWarnList();
		}else{
            $("#tab_faultType").empty();
            $("#tab_unSafeBeh").empty();
            $("#tab_overSpd").empty();
		}
	}

	//TODO==================================================================================================首页部分end=======================================================================================================================


    //TODO==================================================================================================安全部分begin=======================================================================================================================
	/**
	 * 加载车队长安全管理
	 */
	function loadCaptainSafeData(){
		var loadMask = $.createMask();
		$("#safeTabHeader, #safeTabSubHeader, #safeAvgData, #safeHeadTabRow1, " +
		"#safeHeadTabRow2, #safeHeadTabRow3, #safeHeadTabRow4, #safeHeadTabRow5, " +
		"#safeLastTabRow1, #safeLastTabRow2, #safeLastTabRow3, #safeLastTabRow4, #safeLastTabRow5").html('');
		
		if(fuelTypeCode != '')
			params.fuelTypeCode = fuelTypeCode;
		else{
			params.fuelTypeCode = $('#safeOilType').attr('val');
//			fuelTypeCode = $('#safeOilType').attr('val');
		}
		if(safeType=='1'){
			//修改表头
			$("#safeTabHeader").html('<th colspan="2" rowspan="2" width="">排名</th>'+
					'<th rowspan="2">车牌号</th><th rowspan="2">线路</th><th rowspan="2">行驶里程数</th>'+
					'<th rowspan="2">百公里能耗</th><th rowspan="2">故障总数</th><th colspan="5">不安全行为</th>');
			$("#safeTabSubHeader").html('<th><span class="tag-red">严重故障</span></th><th>'+
				'<span class="tag-yellow">一般故障</span></th><th><span class="tag-green">警告故障</span></th>');
			//平均数据
			getAjaxData("/homeCaptain/getFaultsRankCount.htm", function(data){
				if(data){
					$("#safeAvgData").html('<td colspan="2" class="fs-13 hover-none">动态标准值</td>'+
							'<td></td><td></td><td>'+(data.totRngMile?data.totRngMile:0)+'</td><td>'
							+(data.enerConsPer?data.enerConsPer:0)+'</td><td>'+(data.totalFaultCount?data.totalFaultCount:0)
							+'</td><td>'+(data.seriousFaultCount?data.seriousFaultCount:0)+'</td><td>'+
							(data.normalFaultCount?data.normalFaultCount:0)+'</td><td>'+(data.alermFaultCount?data.alermFaultCount:0)+'</td>');
					params.order = 'ASC';
					createSafeFaultTab('优     <br> 秀', '#safeHeadTabRow', 'good');
					params.order = 'DESC';
					createSafeFaultTab('待<br>改<br>进', '#safeLastTabRow', 'bad', loadMask);
				}else{
					loadMask.remove();
				}
			});
		}else if(safeType=='2'){
			var drvSctBhv = [];
			//修改表头
			$("#safeTabHeader").html('<th colspan="2" rowspan="2" width="">排名</th>'+
					'<th rowspan="2">姓名</th><th rowspan="2">车牌号</th><th rowspan="2">线路</th>'+
					'<th rowspan="2">行驶里程数</th><th rowspan="2">百公里能耗</th><th rowspan="2">不安全行为数</th>'+
					'<th rowspan="2" class="c-red">超速</th><th colspan="5">不安全行为</th>');
			$("#safeTabSubHeader").html('<th>-</th><th>-</th><th>-</th><th>-</th><th>-</th>');
			//平均数据
			getAjaxData("/homeCaptain/getDriverUnsafeRankCount.htm", function(data){
				if(data){
					var totRngMile = data[0].totRngMile ? data[0].totRngMile : 0;
					var enerConsPer = data[0].enerConsPer ? data[0].enerConsPer : 0;
					var totalUnsafeCount = data[0].totalUnsafeCount ? data[0].totalUnsafeCount : 0;
					var overSpdCount = data[0].overSpdCount ? data[0].overSpdCount : 0;
					var headHtm = '<td colspan="2" class="fs-13 hover-none">动态标准值</td>'+
					'<td></td><td></td><td></td><td>'+totRngMile+'</td><td>'+enerConsPer+'</td>'+
					'<td>'+totalUnsafeCount+'</td><td>'+overSpdCount+'</td>';
					var html = "";
					if(data.length >1){
						$.each(data, function(index, item){
							html += "<th>"+item.codeDsc+"</th>";
							headHtm += '<td>'+item.hnvCount+'</td>';
							drvSctBhv.push(item.drvSctBhv);
						});
					}else{
						html += "<th>-</th>";
						headHtm += '<td>-</td>';
						drvSctBhv.push('-');
					}
					$("#safeTabSubHeader").html(html);
					$("#safeAvgData").html(headHtm);
					params.drvSctBhv = drvSctBhv;
					params.order = 'ASC';
					createSafeBhvTab('优     <br> 秀', '#safeHeadTabRow', 'good', drvSctBhv);
					params.order = 'DESC';
					createSafeBhvTab('待<br>改<br>进', '#safeLastTabRow', 'bad', drvSctBhv, loadMask);
				}else{
					loadMask.remove();
				}
			});
		}
		//故障饼图
		params.idxType="020401";
		createPieChart("/homeCaptain/getFaultsChart.htm", $("#faultRankingChart"), "故障排名");
		//不安全行为饼图
		params.idxType="020601";
		createPieChart("/homeCaptain/getUnsafeBhvChart.htm", $("#unsafeRankingChart"), "不安全行为排名");
	}
	
	/**
	 * 拼接安全管理故障排名
	 */
	function createSafeFaultTab(title, rowObjStr, css, obj){
		getAjaxData("/homeCaptain/getFaultsRanking.htm", fn = function(data){
			if(data){
				$.each(data, function(index, item){
					var html="";
					html = '<td width="10%" class="'+css+'-num hover-none">'+item.rank+'</td><td>'+item.licPltNo+'</td><td width="12%">'
					+item.lineName+'</td><td width="12%">'+item.totRngMile+'</td><td width="12%">'+item.enerConsPer+'</td><td width="12%">'
					+item.totalFaultCount+'</td><td width="10%">'+item.seriousFaultCount+'</td><td width="10%">'+item.normalFaultCount
					+'</td><td width="10%">'+item.alermFaultCount+'</td>' + html;
					if(index == 0){
						html = '<td rowspan="5" width="26" class="'+css+'-td">'+title+'</td>'+html;
					}
					$(rowObjStr + (index+1)).html(html);
				});
			}
			if(obj){
				obj.remove();
			}
		});
	}
	
	/**
	 * 拼接安全管理不安全行为排名
	 */
	function createSafeBhvTab(title, rowObjStr, css, drvSctBhv, obj){
		getAjaxData("/homeCaptain/getDriverUnsafeRanking.htm", fn = function(data){
			if(data){
				var totRngMile, enerConsPer, totalUnsafeCount, overSpdCount;
				$.each(data, function(index, item){
					var html="";
					if(index == 0){
						html += '<td rowspan="5" width="26" class="'+css+'-td">'+title+'</td>';
					}
					totRngMile = item.totRngMile ? item.totRngMile : 0;
					enerConsPer = item.enerConsPer ? item.enerConsPer : 0;
					totalUnsafeCount = item.totalUnsafeCount ? item.totalUnsafeCount : 0;
					overSpdCount = item.overSpdCount ? item.overSpdCount : 0;
					drvName = item.drvName ? item.drvName : '';
					html += '<td width="10%" class="'+css+'-num hover-none">'+item.rank+'</td><td>'+drvName+'</td><td>'+item.licPltNo+'</td><td>'
					+item.lineName+'</td><td>'+totRngMile+'</td><td>'+enerConsPer+'</td><td>'
					+totalUnsafeCount+'</td><td>'+overSpdCount+'</td>';
					if(item.bhv0count)
						html += '<td>'+item.bhv0count+'</td>';
					else if(drvSctBhv.length>0)
						html += '<td>-</td>';
					if(item.bhv1count)
						html += '<td>'+item.bhv1count+'</td>';
					else if(drvSctBhv.length>1)
						html += '<td>-</td>';
					if(item.bhv2count)
						html += '<td>'+item.bhv2count+'</td>';
					else if(drvSctBhv.length>2)
						html += '<td>-</td>';
					if(item.bhv3count)
						html += '<td>'+item.bhv3count+'</td>';
					else if(drvSctBhv.length>3)
						html += '<td>-</td>';
					if(item.bhv4count)
						html += '<td>'+item.bhv4count+'</td>';
					else if(drvSctBhv.length>4)
						html += '<td>-</td>';
					$(rowObjStr + (index+1)).html(html);
				});
			}
			if(obj){
				obj.remove();
			}
		});
	}
	
	/**
	 * 生成饼图
	 */
	function createPieChart(url, obj, name){
		initParams();
    	var dataAr = [];
        $.ajaxExt({
            url: url,
            data : params
        }).done(function (data) {
        	obj.empty();
        	if(data && data.length > 0 && data[0].tendencyName){
        		for (var i = 0; i < data.length; i++) {
        			dataAr.push([(data[i].tendencyName? data[i].tendencyName : "未知"), parseInt(data[i].tendencyCounts) || 0]);
        		}
        		obj.highcharts({
        			chart: {
        				height: 340
        			},
        			title: {text: ''},
        			credits: {
        				enabled: false
        			},
        			tooltip: {
        				formatter: function () {
        					return '<b>' + this.point.name + '</b>: ' + Highcharts.numberFormat(this.percentage, 1) + '% (' +
        					Highcharts.numberFormat(this.y, 0, ',') + ' 次)';
        				}
        			},
        			plotOptions: {
        				pie: {
        					allowPointSelect: true,
        					cursor: 'pointer',
        					dataLabels: {
        						enabled: true,
        						color: '#000000',
        						connectorColor: '#000000',
        						format: '<b>{point.name}</b>: {point.percentage:.1f}%,{point.y}次 '
        					}
        				}
        			},
        			series: [{
        				type: 'pie',
        				name: name,
        				data: dataAr
        			}]
        		});
        	}
        });
    }
	//TODO==================================================================================================安全部分end=======================================================================================================================


    //TODO==================================================================================================能耗部分begin=======================================================================================================================
    /**
	 * 生成车队长能耗部分
     */
	function loadCaptainEnergyData(){
		var loadMask = $.createMask();
		$("#enerAvgTab, #enerHeadRow1, #enerHeadRow2, #enerHeadRow3, #enerHeadRow4, #enerHeadRow5," +
		 "#enerLastRow1, #enerLastRow2, #enerLastRow3, #enerLastRow4, #enerLastRow5").empty();
		$("#enerBhvHeader1, #enerBhvHeader2, #enerBhvHeader3").html("-");
		//变更表头
		var tabHeadHtml = '<th colspan="2" rowspan="2" width="">排名</th>';
		var avgHtml = '<td colspan="2" class="fs-13 hover-none">动态标准值</td><td>&nbsp;</td><td>&nbsp;</td>';
		if(fuelTypeCode != '')
			params.fuelTypeCode = fuelTypeCode;
		else
			params.fuelTypeCode = $('#enerOilType').attr('val');
		if(groupType == 'DRVER'){
			tabHeadHtml += '<th rowspan="2">司机</th>';
			avgHtml += '<td>&nbsp;</td>';
		}
		tabHeadHtml += '<th rowspan="2">车牌号</th><th rowspan="2">线路</th><th rowspan="2">行驶里程数</th><th rowspan="2">百公里能耗</th>'
			+'<th rowspan="2">百公里节能</th><th colspan="3">车辆转速</th><th colspan="3">车辆行为</th>';
		$("#enerHeadTab").html(tabHeadHtml);
		//能耗平均值
		getEnergyAvgVal(avgHtml, loadMask);
		
		//能耗趋势
		getFullDate();
		energyTendencyChart("油", "010701", $("#oilTendencyChart"), '#FF5151', "L");
		energyTendencyChart("电", "010702", $("#elecTendencyChart"), '#79FF79', "KWH");
		energyTendencyChart("气", "010703", $("#gasTendencyChart"), '#FF9224', "L");
		//能耗模型
		createEnergyModelPie('/homeCaptain/getEnergyStatusPieChart.htm', $('#energyModelChart'));
		//能耗结论
		params.idxType = idxType;
		getEnergyConclude();
		
		//能耗问题
		params.idxType = '031302';
		getAjaxData("/homeCaptain/getEnerMultiInfo.htm", function(data){
			if(data){
				var html = '<strong class="c-red">驾驶过程中，平均每车每小时的：</strong>';
				$.each(data, function(index, item){
					html += '<br>'+item.energyEffectItem+'（'+item.occurCount+'）';
				});
				$("#energyRiseDrv").html(html);
			}
		});
		params.idxType = '031303';
		getAjaxData("/homeCaptain/getEnerMultiInfo.htm", function(data){
			if(data){
				var html = '<strong class="c-red">车辆自身，平均每车每小时的：</strong>';
				$.each(data, function(index, item){
					html += item.energyEffectItem+'次数达到'+item.occurCount+'次';
				});
				$("#energyRiseCar").html(html);
			}
		});
		//能耗建议
		params.idxType = '031304';
		getAjaxData("/homeCaptain/getEnerMultiInfo.htm", function(data){
			if(data){
				var html = '<strong class="c-red">调整驾驶行为：</strong>';
				$.each(data, function(index, item){
					html += '<br>'+item.energyEffectItem+'控制在'+item.occurCount;
				});
				$("#energyAdviceDrv").html(html);
			}
		});
		params.idxType = '031305';
		getAjaxData("/homeCaptain/getEnerMultiInfo.htm", function(data){
			if(data){
				var html = '<strong class="c-red">做好维修保养，避免出现：</strong>';
				$.each(data, function(index, item){
					html += '<br>'+item.energyEffectItem+item.occurCount+'问题';
				});
				$("#energyAdviceCar").html(html);
			}
		});
	}

    /**
     * 车队长能耗均值
     */
	function getEnergyAvgVal(avgHtml, loadMask){
		getAjaxData("/homeCaptain/getAvgEnergyVal.htm", function(data){
			if(data && data.length > 0){
				var drvSctAr = [];
				avgEnerConsPer = data[0].avgEnerConsPer;
				var otherCount = data[0].totalCount - data[0].idliCount - data[0].lowEnerAreaDriveCount;
				avgHtml += '<td>'+(data[0].avgTotalMile?data[0].avgTotalMile:0)+'</td><td>'
					+(data[0].avgEnerConsPer?data[0].avgEnerConsPer:0)+'</td><td>-</td><td>'
					+(data[0].idliCount?data[0].idliCount.toFixed(2):0)+'</td><td>'
					+(data[0].lowEnerAreaDriveCount?data[0].lowEnerAreaDriveCount.toFixed(2):0)+'</td><td>'
					+(isNaN(otherCount)?0:otherCount.toFixed(2))+'</td>';
				
				if(data[0] && data[0].bhvCount){
					avgHtml += '<td>'+data[0].bhvCount+'</td>';
					$("#enerBhvHeader1").html(data[0].drvSctDsc);
					drvSctAr.push(data[0].drvSctBhv);
				}else{
					avgHtml += '<td>-</td>';
				}
				
				if(data[1] && data[1].bhvCount){
					avgHtml += '<td>'+data[1].bhvCount+'</td>';
					$("#enerBhvHeader2").html(data[1].drvSctDsc);
					drvSctAr.push(data[1].drvSctBhv);
				}else{
					avgHtml += '<td>-</td>';
				}
				if(data[2] && data[2].bhvCount){
					avgHtml += '<td>'+data[2].bhvCount+'</td>';
					$("#enerBhvHeader3").html(data[2].drvSctDsc);
					drvSctAr.push(data[2].drvSctBhv);
				}else{
					avgHtml += '<td>-</td>';
				}
				$("#enerAvgTab").html(avgHtml);
				
				params.drvSctBhv = drvSctAr;
				params.order = 'ASC';
				createEnergyRankingTab('优<br> 秀', "#enerHeadRow", avgEnerConsPer, 'good');
				params.order = 'DESC';
				createEnergyRankingTab('待<br>改<br>进', "#enerLastRow", avgEnerConsPer, 'bad', loadMask);
			}else{
				loadMask.remove();
			}
		}, false);
	}
	
	/**
	 * 能耗结论
	 */
	function getEnergyConclude(){
		getAjaxData("/homeCaptain/getEnergyConclude.htm", function(data){
			$("#energyConclude").empty();
			var unit = "L",
				concludeType="油";
			if(params.idxType == '030103'){
				unit = "L", concludeType = "气";
			}else if(params.idxType == '030102'){
				unit = "KWH", concludeType = "电";
			}
			fillEnergyConclude(data[0].energyConsum, unit, data[0].energyMomPer, (data[0].energyYoyPer ? data[0].energyYoyPer : 0), concludeType);
		});
	}

	/**
	 * 填充能耗结论
	 * @param energyVal 能耗值
	 * @param unit 单位
	 * @param energyPerMonth 环比
	 * @param energyPerYear 同比
	 * @param type 燃料类型
	 */
	function fillEnergyConclude(energyVal, unit, energyPerMonth, energyPerYear, type){
		if(isNaN(parseFloat(energyVal))){
			energyVal = "0";
		}
		if(isNaN(parseFloat(energyPerMonth))){
			energyPerMonth = "0";
		}
		if(isNaN(parseFloat(energyPerYear))){
			energyPerYear = "0";
		}
		var html = "平均"+type+"耗为"+energyVal+unit+"，";
		if(energyPerYear>0){
			html += "同比<strong class='c-red'>上升"+energyPerYear+"%</strong>，";
		}else if(energyPerYear<0){
			html += "同比<strong class='c-green'>下降"+energyPerYear+"%</strong>，";
		}else{
			html += "同比<strong>"+energyPerYear+"%</strong>，";
		}
		if(energyPerMonth>0){
			html += "环比<strong class='c-red'>上升"+energyPerMonth+"%</strong>，<br>";
		}else if(energyPerMonth<0){
			html += "环比<strong class='c-green'>下降"+energyPerMonth+"%</strong>，<br>";
		}else{
			html += "环比<strong>"+energyPerMonth+"%</strong>;<br>";
		}
		$("#energyConclude").append(html);
	}

	/**
	 * 拼接能耗排名
	 */
	function createEnergyRankingTab(title, obj, avgEnerConsPer, css, mask){
		console.info(params);
		getAjaxData("/homeCaptain/getEnergyRanking.htm", function(data){
			if(data){
				$.each(data, function(index, item){
					var energyHeadTab = '';
					var otherCount = item.totalCount - item.idliCount - item.lowEnerAreaDriveCount;
					if(index == 0){
						energyHeadTab += '<td rowspan="5" width="26" class="'+css+'-td">'+title+'</td>';
					}
                    energyHeadTab += '<td width="5%" class="'+css+'-num hover-none">'+item.rank+'</td>';
					if(params.type == 'DRVER'){
                        if(item.drvName){
                            energyHeadTab += '<td width="5%">'+item.drvName+'</td>';
                        }else{
                            energyHeadTab += '<td width="5%">未知司机</td>';
						}

                    }
					var saveEnergyPer = (item.enerConsPer - avgEnerConsPer)*100/avgEnerConsPer;
					// if(groupType == 'DRVER'){
					// 	energyHeadTab += '<td>'+(item.drvName?item.drvName:'')+'</td>';
					// }
					console.info(item);
					energyHeadTab += '<td>'+item.licPltNo+'</td><td>'+item.lineName+'</td><td>'+item.totRngMile
					+'</td><td>'+item.enerConsPer+'</td><td>'+saveEnergyPer.toFixed(2)+'%</td><td>'+item.idliCount
					+'</td><td>'+item.lowEnerAreaDriveCount+'</td><td>'+otherCount+'</td>';
					if(item.bhv0count)
						energyHeadTab += '<td>'+item.bhv0count+'</td>';
					else //if(item.bhv0count.length>0)
						energyHeadTab += '<td>-</td>';
					if(item.bhv1count)
						energyHeadTab += '<td>'+item.bhv1count+'</td>';
					else //if(item.bhv1count.length>1)
						energyHeadTab += '<td>-</td>';
					if(item.bhv2count)
						energyHeadTab += '<td>'+item.bhv2count+'</td>';
					else //if(item.bhv2count.length>2)
						energyHeadTab += '<td>-</td>';
					$(obj+(index+1)).html(energyHeadTab);
				});
			}
			if(mask){
				mask.remove();
			}
		});
	}
	
	/**
	 * 能耗趋势
	 */
	function energyTendencyChart(title, energyIndex, obj, color, unit){
		params.idxType = energyIndex;
		getAjaxData("/homeCaptain/getEnergyTendencyCharts.htm", function(data){
			var category = [],
				series = [{name:"百公里"+title+"耗", data:[]}],
				mainTitle = '百公里'+title+'耗趋势';
			//数据格式
			formatEnergyTendencyData(data, dateType, category, series, dateAr);
			//趋势图
			createEnergyTendencyChart(obj, "areaspline", color, mainTitle, "", category, unit, series, dateType, energyIndex, data);
		});
	}

    /**
	 * 能耗模型饼图
     * @param url
     * @param obj
     */
	function createEnergyModelPie(url, obj){
		var dataAr = [];
		$.ajaxExt({
			url:url,
			data:params
		}).done(function(data){
			$("#energyStatusPieChart").empty();
			if(data && data.length>0){
				for(var i = 0; i < data.length; i++){
					dataAr.push([data[i].propertyItem, parseInt(data[i].propertyVal)||0]);
				}
				Highcharts.setOptions({  
					colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', 
					         '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1']
				}); 
				obj.highcharts({ 
					chart: { plotBackgroundColor: null, 
						plotBorderWidth: null,
						plotShadow: false }, 
						credits: {
							enabled: false
						},
						title: { text: '能耗特征模型分析' }, 
						tooltip: { formatter: function() {
							return '<b>'+ this.point.name +'</b>: '+ Highcharts.numberFormat(this.percentage, 1) +'%';
						}}, 
						plotOptions: { 
							pie: { allowPointSelect: true, 
								cursor: 'pointer', 
								dataLabels: { enabled: true, 
									color: '#000000', 
									connectorColor: '#000000', 
									format: '<b>{point.name}</b>: {point.y} %' 
								} 
							} 
						}, 
						series: [{ type: 'pie', 
							name: '能耗特征模型分析', 
							data: dataAr
						}]
				});
			}
		});
	}
    //TODO==================================================================================================能耗部分end=======================================================================================================================


    //TODO==================================================================================================驾驶员部分begin=======================================================================================================================
	/**
	 * 车队长首页驾驶员部分
	 */
	function loadCaptainDriverData(){
		var loadMask = $.createMask();
		$("#drvUnsafeRankCount, #drvHeadTabRow1, #drvHeadTabRow2, #drvHeadTabRow3, #drvHeadTabRow4, #drvHeadTabRow5," +
		"#drvLastTabRow1, #drvLastTabRow2, #drvLastTabRow3, #drvLastTabRow4, #drvLastTabRow5").empty();
		$("#drvTabAvgHead").html('<th>-</th><th>-</th><th>-</th><th>-</th><th>-</th>');
		if(fuelTypeCode != '')
			params.fuelTypeCode = fuelTypeCode;
		else
			params.fuelTypeCode = $('#drvOilType').attr('val');
		//平均数据
		getAjaxData("/homeCaptain/getDriverUnsafeRankCount.htm", function(data){
			if(data){
				var drvSctBhv = [];
				var html = '<td colspan="2" class="fs-13 hover-none">动态标准值</td><td></td><td></td><td></td>'+
				'<td>'+(data[0].totRngMile?data[0].totRngMile:0)+'</td><td>'+(data[0].enerConsPer?data[0].enerConsPer:0)+'</td><td>'
				+(data[0].totalUnsafeCount?data[0].totalUnsafeCount:0)+'</td><td>'+(data[0].overSpdCount?data[0].overSpdCount:0)+'</td>';
				var tabHead = '';
				if(data.length>1){
					$.each(data, function(index, item){
						drvSctBhv.push(item.drvSctBhv);
						tabHead += '<th>'+item.codeDsc+'</th>';
						html += '<td>'+item.hnvCount+'</td>';
					});
				}else{
					drvSctBhv.push('-');
					tabHead += '<th>-</th>';
					html += '<td>-</td>';
				}
				$("#drvTabAvgHead").html(tabHead);
				$('#drvUnsafeRankCount').html(html);
				params.drvSctBhv = drvSctBhv;
				//驾驶员排名前五
				params.order = "ASC";
				createDrvRankTab('优<br> 秀', '#drvHeadTabRow', 'good', drvSctBhv);
				//排名后五
				params.order = "DESC";
				createDrvRankTab('待<br>改<br>进', '#drvLastTabRow', 'bad', drvSctBhv, loadMask);
			}else{
				loadMask.remove();
			}
		});
	}

	/**
	 * 生成驾驶员排名报表
	 */
	function createDrvRankTab(title, obj, css, drvSctBhv, mask){
		getAjaxData("/homeCaptain/getDriverUnsafeRanking.htm", function(data){
			if(data){
				$.each(data, function(index, item){
					var html = '';
					if(index == 0){
						html = '<td rowspan="5" width="2%" class="'+css+'-td">'+title+'</td>';
					}
					html += '<td class="'+css+'-num hover-none" width="5%">'+item.rank+'</td><td>'+(item.drvName?item.drvName:'')
					+'</td><td>'+item.licPltNo+'</td><td>'+item.lineName+'</td><td >'
					+(item.totRngMile?item.totRngMile:0)+'</td><td>'+(item.enerConsPer?item.enerConsPer:0)+'</td><td>'
					+(item.totalUnsafeCount?item.totalUnsafeCount:0)+'</td><td>'+(item.overSpdCount?item.overSpdCount:0)+'</td>'
					if(item.bhv0count)
						html += '<td>'+item.bhv0count+'</td>';
					else if(drvSctBhv.length>0)
						html += '<td>-</td>';
					if(item.bhv1count)
						html += '<td>'+item.bhv1count+'</td>';
					else if(drvSctBhv.length>1)
						html += '<td>-</td>';
					if(item.bhv2count)
						html += '<td>'+item.bhv2count+'</td>';
					else if(drvSctBhv.length>2)
						html += '<td>-</td>';
					if(item.bhv3count)
						html += '<td>'+item.bhv3count+'</td>';
					else if(drvSctBhv.length>3)
						html += '<td>-</td>';
					if(item.bhv4count)
						html += '<td>'+item.bhv4count+'</td>';
					else if(drvSctBhv.length>4)
						html += '<td>-</td>';
					$(obj+(index+1)).html(html);
				});
			}
			if(mask){
				mask.remove();
			}
		});
	}
    //TODO==================================================================================================驾驶员部分end=======================================================================================================================


    //TODO==================================================================================================资金部分begin=======================================================================================================================
	/**
	 * 加载资金首页 
	 */
	function loadCaptainFinanceData(){
		initParams();
		$('#financeTab').grid('setGridParam', {
            datatype: "json",
            postData: params
        }).trigger("reloadGrid");
	}

	
	showDataDetail = function (data) {
        openLocationDetailInfoDialog("详细位置", data); //弹出的标题和数据
    };
	
	function openLocationDetailInfoDialog(title, data) {
        if (!locationDetailInfoDialog) {
            locationDetailInfoDialog = $('<div>').dialog({
                title: title,
                url: './common/map/mapLocation.htm',
                height: $(window.parent).height() * 0.8,
                width: $(window.parent).width() * 0.85
            });
        }
        locationDetailInfoDialog.dialog('open');
        locationDetailInfoDialog.dialog('exec', 'showMapLocation', data);
    }
    //TODO==================================================================================================资金部分end=======================================================================================================================

	/**
	 * 异步加载数据
	 */
	function getAjaxData(url, fn, isAsync){
		var async = true;
		if(!isAsync){
			async = isAsync;
		}
		initParams();
		$.ajaxExt({
			url : url,
			async: async,
			data : params
		}).done(fn);
	}
	
	/**
     * 获取日期类型对应日期数据
     */
    function getFullDate(){
    	$.ajaxExt({
    		async : false,
    		url:"/homeTransit/getFullDate.htm",
    		data:{
    			"dateType":dateType,
    			"yesterday":((new Date()).dateAdd('d',-1)).format()
    		}
    	}).done(function(data){
    		if(data && data.length > 0){
    			for(var i =0;i<data.length;i++){
    				dateAr.push(data[i].trendDate);
    			}
    			if(dateType=='02'){
    	    		dateString = ((new Date()).dateAdd('d',-1)).format();
    	    	}else if(dateType == '03'){
    				dateString = data[0].trendDate+"-"+data[data.length-1].trendDate;
    			}else if(dateType == '04' || dateType == '05'){
    				dateString = data[0].trendDate.substring(0, 7)+"月";
    			}else if(dateType == '07' || dateType == '06'){
    				dateString = data[0].trendDate.substring(0, 4)+"年";
    			}
    		}
    	});
    }

    /**
	 * 安全部分中，故障和不安全行为切换
	 * */
	$("#safeFaultType, #safeUnsafeType").click(function(){
		$("#safeFaultType, #safeUnsafeType").removeClass("active");
		$(this).addClass("active");
		safeType = $(this).attr("val");
		if(safeType == '1'){
			//修改表头
			$("#safeTabHeader").html('<th colspan="2" rowspan="2" width="">排名</th>'+
					'<th rowspan="2">车牌号</th><th rowspan="2">线路</th><th rowspan="2">行驶里程数</th>'+
					'<th rowspan="2">百公里能耗</th><th rowspan="2">故障总数</th><th colspan="5">不安全行为</th>');
			$("#safeTabSubHeader").html('<th><span class="tag-red">严重故障</span></th><th>'+
				'<span class="tag-yellow">一般故障</span></th><th><span class="tag-green">警告故障</span></th>');
		}else if(safeType == '2'){
			$("#safeTabHeader").html('<th colspan="2" rowspan="2" width="">排名</th>'+
					'<th rowspan="2">姓名</th><th rowspan="2">车牌号</th><th rowspan="2">线路</th>'+
					'<th rowspan="2">行驶里程数</th><th rowspan="2">百公里能耗</th><th rowspan="2">不安全行为数</th>'+
					'<th rowspan="2" class="c-red">超速</th><th colspan="5">不安全行为</th>');
			$("#safeTabSubHeader").html('<th>-</th><th>-</th><th>-</th><th>-</th><th>-</th>');
		}
		
		if(params.lineIds && params.lineIds.length > 0){
			loadData("captainSafe");
		}
	});

    /**
	 * 大功能之间切换
     */
	$("#captainHome, #captainSafe, #captainEnergy, #captainDriver, #captainFinance").click(function(){
		$(".enerType").removeClass('active');
		if(fuelTypeCode){
			if(fuelTypeTot == '030101'){
				$("#safeOilType, #enerOilType, #drvOilType, #homeOilType").addClass('active');
			}else if(fuelTypeTot == '030103'){
				$("#safeGasType, #enerGasType, #drvGasType, #homeGasType").addClass('active');
			}else if(fuelTypeTot == '030102'){
				$("#safeElecType, #enerElecType, #drvElecType, #homeElecType").addClass('active');
			}
		}else{
			fuelTypeCode = '0,1,6';
			$("#safeOilType, #enerOilType, #drvOilType, #homeOilType").addClass('active');
		}
		
		//改变按钮样式
		$(".item1, .item2, .item3, .item4, .item5").removeClass("active");
		$(this).parent().addClass("active");
		//切换功能区域显示
		$("#captainHomeDiv, #captainSafeDiv, #captainEnergyDiv, #captainDriverDiv, #captainFinanceDiv").hide();
		var idStr = $(this).attr("id");
		$("#"+idStr+"Div").show();
		funcType = idStr;
		//加载对应数据
		var lineNames = [];

        var nodes = treeObj.getCheckedNodes(true);
        if(nodes && nodes.length > 0){
            $.each(nodes, function(index, item){
                if(item.type == 'LINE'){
                    lineNames.push(item.name);
                }
            });
        }

		// $("input[name='lineChk']:checked").each(function(){
		// 	lineNames.push($(this).attr('dscVal'));
		// });
		
		if(lineNames && lineNames.length > 0){
			if(dateType == '02'){
				$('#dateDiv').find('a:first').addClass('active');
			}
			loadData(idStr);
		}
	});
	
	//日期按钮设置
	$("#dateDiv").find('a').click(function(){
		$("#dateDiv").find('a').removeClass("active");
		dateType = $(this).attr("val");
		dateAr = [];
		//加载页面各项
		$(this).addClass("active");
		loadData(funcType);
	});

	/**
	 * 能耗类型
	 */
	$("#safeOilType, #safeGasType, #safeElecType, " +
	  "#enerOilType, #enerGasType, #enerElecType, " + 
	  "#drvOilType, #drvGasType, #drvElecType, "+
	  "#homeOilType, #homeGasType, #homeElecType").click(function(){
        var selLines = [];

        var nodes = treeObj.getCheckedNodes(true);
        if(nodes && nodes.length > 0){
            $.each(nodes, function(index, item){
                if(item.type == 'LINE'){
                    selLines.push(item.id);
                }
            });
        }

        // $("input[name='lineChk']:checked").each(function(){
        //     selLines.push($(this).val());
        // });
        if(selLines.length > 0){
            if(dateType == '02'){
                $('#dateDiv').find('a:first').addClass('active');
            }
            $(".enerType").removeClass('active');
            $(this).addClass('active');
            fuelTypeCode = $(this).attr('val');
            fuelTypeTot = $(this).attr('indexType');
            //TODO
            params.idxType = $(this).attr('indexType');
            idxType = $(this).attr('indexType');
            if($(this).attr('id') == 'enerOilType' || $(this).attr('id') == 'enerGasType' || $(this).attr('id') == 'enerElecType'){
                $("#enerAvgTab, #enerHeadRow1, #enerHeadRow2, #enerHeadRow3, #enerHeadRow4, #enerHeadRow5," +
                    "#enerLastRow1, #enerLastRow2, #enerLastRow3, #enerLastRow4, #enerLastRow5").empty();
                $("#enerBhvHeader1, #enerBhvHeader2, #enerBhvHeader3").html("-");
                params.fuelTypeCode = fuelTypeCode;

                var loadMask = $.createMask();
                var avgHtml = '<td colspan="2" class="fs-13 hover-none">动态标准值</td><td>&nbsp;</td><td>&nbsp;</td>';
                if(groupType == 'DRVER'){
                    avgHtml += '<td>&nbsp;</td>';
                }
                getEnergyAvgVal(avgHtml, loadMask);
                getEnergyConclude();
            }else{
                loadData(funcType);
            }
        }else{
            $.messager.alert("警告","请先选择线路！","info");
		}
	});
	
	/**
	 * 能耗分组类型
	 */
	$("#enerCarType, #enerDrvType").click(function(){
		//TODO
		if(dateType == '02'){
			$('#dateDiv').find('a:first').addClass('active');
		}
		$("#enerCarType, #enerDrvType").removeClass("active");
		$(this).addClass("active");
		groupType = $(this).prop("type");
		//params.type = groupType;
		var lineNames = [];

        var nodes = treeObj.getCheckedNodes(true);
        if(nodes && nodes.length > 0){
            $.each(nodes, function(index, item){
                if(item.type == 'LINE'){
                    lineNames.push(item.name);
                }
            });
        }

		// $("input[name='lineChk']:checked").each(function(){
		// 	lineNames.push($(this).attr('dscVal'));
		// });
		if(lineNames && lineNames.length > 0){
			loadData(funcType);
		}
	});

	$(function(){
        (function(){
            var _int;
            $('.line-display-area').hover(function(){
                var _t = this;
                _int && clearInterval(_int);
                _int = setTimeout(function(){
                    $('.all-show',_t).show();
                },500);
            },function(){
                var _t = this;
                _int && clearInterval(_int);
                _int = setTimeout(function(){
                    $('.all-show',_t).hide();
                },400);
            });
        }());
    });

	$(".line-select-area").click(function(){
		if($(this).hasClass("line-select-default")) {
			$(".line-select-container").stop().animate({
				"left": 158
			},400);
			$(this).removeClass("line-select-default");
		} else {
			$(".line-select-container").stop().animate({
				"left": -127
			},400);
			$(this).addClass("line-select-default");
		}
	});

	$(".pull-left-arrow").click(function(){
		$(".line-select-container").stop().animate({
				"left": 0
			},400); 
			$(".line-select-area").addClass("line-select-default");
	});
	
	
	$(".main-value .slide-btn").click(function(){
		if(!$(this).find(".up").hasClass("down")) {
			$(".main-value").stop().animate({
				"top": "-313px"
			},500);
			$(this).find(".up").addClass("down");
		} else {
			$(".main-value").stop().animate({
				"top": "0"
			},500);
			$(this).find(".up").removeClass("down");
		}
	});

    /**
	 * 定时刷新地图相关信息
     */
	$("#refreshIntev").change(function(){
        $("#tab_faultType").empty();
        $("#tab_unSafeBeh").empty();
        $("#tab_overSpd").empty();
		if(interval){
			clearInterval(interval);
		}
		if(params.lineIds && params.lineIds.length > 0){
			loadfMapInfo();
		}
	});

    /**
	 * 自动刷新定时
     */
	$("#autoLoad").click(function(){
        $("#tab_faultType").empty();
        $("#tab_unSafeBeh").empty();
        $("#tab_overSpd").empty();
		if(interval){
			clearInterval(interval);
		}
		if($(this).is(':checked')){
			loadfMapInfo();
		}
	});

    /**
	 * 展示地图信息事件
     */
	$("#checkCurrentCarInfo").click(function(){
        $("#tab_faultType").empty();
        $("#tab_unSafeBeh").empty();
        $("#tab_overSpd").empty();
		if(interval){
			clearInterval(interval);
		}
		if(dateType == '02'){
			$('#dateDiv').find('a:first').addClass('active');
		}
		loadData(funcType);
		if(funcType == 'captainHome'){
			loadfMapInfo();
		}
		$(".line-select-area").click();
	});

    /**
	 * 加载地图信息
     */
	function loadfMapInfo(){
		map.clearMap();
		initParams();
		$.each(params.lineIds, function(index, item){
			loadLineCity(item, tmpLineNames[index]);
		});
		var intevals = $("#refreshIntev").val();
		params.timeFrequence = intevals;
		updateMapInfo();
		if($("#autoLoad").is(':checked')){
			interval = setInterval(function(){
				updateMapInfo();
			}, intevals*1000);
		}
	}

	//跳转
    //TODO=================================================================================================================跳转其他功能
	$("#faultRankingMore").click(function(){
			var data = {};
			data.lineIds = params.lineIds;
			data.dateType = params.dateType;
			data.statisType = 'FAULT';
			data.mftTypeCode = "";
			$.openTab('4270f3bb02fa4bf0bab5f40a351ae747', 'searchFaultSummery', [data]);
	});
	
	$("#unsafeRankingMore").click(function(){
		var data = {};
		data.lineIds = params.lineIds;
		data.dateType = params.dateType;
		data.statisType = 'LINE';
		$.openTab('0faa7a5b3279477b813cefe5a5362bd1', 'searchUnsafeSummery', [data]);
	});
	
	$("#wholeSafeRank").click(function(){
		if(safeType == 1){
			var data = {};
			data.statisType = 'CAR';
			data.lineIds = params.lineIds;
			data.dateType = params.dateType;
			data.mftTypeCode = "";
			$.openTab('4270f3bb02fa4bf0bab5f40a351ae747', 'searchFaultSummery', [data]);
		}else{
			var data = {};
			data.lineIds = params.lineIds;
			data.dateType = params.dateType;
			data.statisType = 'LINE';
			$.openTab('0faa7a5b3279477b813cefe5a5362bd1', 'searchUnsafeSummery', [data]);
		}
	});
	
	$("#wholeDrvRanking").click(function(){
		var data = {};
		data.lineIds = params.lineIds;
		data.dateType = params.dateType;
		data.statisType = 'LINE';
		$.openTab('0faa7a5b3279477b813cefe5a5362bd1', 'searchUnsafeSummery', [data]);
	});
	
	$("#wholeEnergyRanking").click(function(){
		var id ='d280237883a94d72a90530e4ace3931d';
		if(groupType == 'DRVER'){
			id = '22a8cf4a8bef40ca9231911bce49d01b';
		}
		var data = {};
		var energyTypeCode = [];
			energyTypeCode = ['1', '2'];
		if(params.fuelTypeCode == '4,5'){
			energyTypeCode = ['4', '5'];
		}else if(params.fuelTypeCode == '3'){
			energyTypeCode = ['3'];
		}
		data.energyType = energyTypeCode;
		data.energyTimeType = '';
		if(dateType == '06' || dateType == '07'){
			data.energyTimeType = '7';
		}
		data.lineIds = params.lineIds;
		data.dateType = dateType;
		$.openTab(id, 'searchEnergyDetail', [data]);
	});

	$("#more_faultType").click(function(){
        var data = {};
        // var nodes = treeObj.getCheckedNodes(true);
        // if(nodes && nodes.length > 0){
        //     $.each(nodes, function(index, item){
        //         if(item.type == 'LINE'){
        //             lineIds.push(item.id);
        //         }
        //     });
        // }
		data.lineIds = params.lineIds;
        $.openTab('c60acb21701a4b63ba3e6d9ddd502ab0', 'captainTodaySearch', [data]);
	});

    $("#more_unSafeBeh").click(function(){
        var data = {};
        data.lineIds = params.lineIds;
        $.openTab('9e9e90184a644a069ece59eca8cae9fe', 'captainTodaySearch', [data]);
    });

    $("#more_overSpd").click(function(){
        var data = {};
        data.lineIds = params.lineIds;
        $.openTab('82574146a7d34a1bb4423bafbeddbe21', 'captainTodaySearch', [data]);
    });

	$("#selAll").click(function(){
		$("#lineChkBox").find(':checkBox').prop("checked", this.checked);
		if(this.checked){
			$("#showSelectLines").html('<a>全部线路</a>');
			$('.all-show').html('<a>全部线路</a>');
		}else{
			$("#showSelectLines").empty();
			$('.all-show').empty();
		}
	});
	
	//TODO=================================================================================================================地图部分
	/*
	 * 创建地图
	 */
	function createMap(){
    	downCircleAreaAr = [];
    	upCircleAreaAr = [];
    	map = new AMap.Map("iCenter", {
            resizeEnable: true,
            scrollWheel: true,
            zoom: 13 
        });
        toolBar = new AMap.ToolBar({
        	ruler:true
        });
        map.addControl(toolBar);
    }

	/**
	 * 获取线路下所有车辆最后位置
	 */
	var contentMark = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30), autoMove:false});

    /**
	 * 获取车辆最后位置
     */
	function getLineCarLastPosition(){
		getAjaxData("/homeCaptain/getLineCarLastPosition.htm", function(data){
			if(data){
				//移除车辆
				$.each(carMarkers, function(index, item){
					item.setMap(null);
				});
				carMarkers = [];
				$.each(data, function(index, item){
					var carImg = "/content/images/car_gpsOnline.png";
					if(item.upDn == '1'){
						carImg = "/content/images/car_online2.png";
					}
					var carMarker = new AMap.Marker({
				        map: map,
				        draggable: false, // 是否可拖动
				        position: new AMap.LngLat(item.loLgt, item.loLtt),// 基点位置
				        offset: new AMap.Pixel(-12, -9),
				        icon: $.getProjectName() + carImg,
				        angle: parseFloat(item.loDrc) - 90,
				        autoRotation: true
				    });
					var content = item.licPltNo + '</br>车速：' + item.spdOfMotVhi + 'Km/h';
					if(item.upDn == '0'){
                        content += ' 上行</br>';
					}else{
                        content += ' 下行</br>';
					}
					if(item.drvName){
                        content += '驾驶员:' + item.drvName + '</br>';
					}else{
                        content += '驾驶员: - </br>';
					}
					if(item.carType == 'CAT00007' || item.carType == 'CAT00004'){
                        content += 'SOC:'+item.soc+"</br>";
					}
					carMarker.content = content;
					carMarker.loLgt = item.loLgt;
					carMarker.loLtt = item.loLtt;
                    carMarker.carId = item.carId;
					AMap.event.addListener(carMarker, 'mouseover', showInfo);
				    AMap.event.addListener(carMarker, 'mouseout', closeShowInfo);
					carMarkers.push(carMarker);
				});
			}
		});
	}

	function showInfo(e){
		if (e.target.content && e.target.content != "") {
            params.carId = e.target.carId;
            var content = e.target.content;
            $.ajaxExt({
				url:"/homeCaptain/getRecentlyWarn.htm",
				data:params
			}).done(function(data){
				if(data.mftOccurTime && data.mftOccurTime > (data.sctBhvBeginTime||'') && data.mftOccurTime > (data.spdingBeginTime||'')){
                    content += '最近发生报警：' + data.mftTypeName + '</br>发生时间:' + data.mftOccurTime;
				}else if(data.sctBhvBeginTime && data.sctBhvBeginTime > (data.mftOccurTime||'') && data.sctBhvBeginTime > (data.spdingBeginTime||'')){
                    content += '最近发生报警：' + data.bhvDsc + '</br>发生时间:' + data.sctBhvBeginTime;
				}else if(data.spdingBeginTime && data.spdingBeginTime > (data.mftOccurTime||'') && data.spdingBeginTime > (data.sctBhvBeginTime||'')){
                    content += '最近发生报警：' + data.warnType + '</br>发生时间:' + data.spdingBeginTime;
				}
                contentMark.close();
                contentMark.content = content;
                contentMark = new AMap.InfoWindow({content: content, offset: new AMap.Pixel(0, -30), autoMove:false});
                contentMark.open(map, new AMap.LngLat(e.target.loLgt, e.target.loLtt));
			});
            contentMark = new AMap.InfoWindow({content: content, offset: new AMap.Pixel(0, -30), autoMove:false});
            contentMark.open(map, new AMap.LngLat(e.target.loLgt, e.target.loLtt));
        }
	}
	
	function closeShowInfo(){
		if (contentMark) {
			contentMark.close();
        }
	}
	
	/**
	 * 获取每辆车最新报警信息
	 */
	function getRecentWarnInfo(){
		getAjaxData("/homeCaptain/getRecentWarnInfo.htm", function(data){
			if(data){
				if(faultMarkers){
					$.each(faultMarkers, function(index, item){
						item.setMap(null);
					});
				}
				if(unsafeMarkers){
					$.each(unsafeMarkers, function(index, item){
						item.setMap(null);
					});
				}
				if(overspeedMarkers){
					$.each(overspeedMarkers, function(index, item){
						item.setMap(null);
					});
				}
				faultMarkers = [],
				unsafeMarkers = [],
				overspeedMarkers = [];
				$.each(data, function(index, item){
					if(item.fLgt){
						var faultMarker = new AMap.Marker({
					        map: map,
							position: [item.fLgt, item.fLtt],
							icon: new AMap.Icon({            
					            size: new AMap.Size(35, 32),  //图标大小
					            image: $.getProjectName() + "/content/images/map-waring.png"
					            	/**/
					        }) 
					    });
						faultMarker.on('click', function(){
							var content = '<div>故障报警：'+item.mftTypeName+'</div><ul><li>'
							+'<label>车辆：</label><p>'+item.lineName+'-'+item.licPltNo+'</p></li><li>'
							+'<label>车速：</label><p>'+item.faultSpeed+'(km/s)</p></li><li><label>转速：</label>'
							+'<p>'+item.faultRtteSpd+'转速(rpm)</p></li></ul></div>';
							var faultWindow = new AMap.InfoWindow({
								content: content,
								offset: new AMap.Pixel(16, -45)
							});
							faultWindow.open(map, [item.fLgt, item.fLtt]);
						});
						faultMarkers.push(faultMarker);
					}
					
					//不安全行为
					if(item.bLgt){
						var unsafeMarker = new AMap.Marker({
					        map: map,
							position: [item.bLgt, item.bLtt]
					    });
						unsafeMarker.on('click', function(){
							content = '<div>不安全行为：'+item.bhvDsc+'</div><ul><li>'
							+'<label>车辆：</label><p>'+item.lineName+'-'+item.licPltNo+'</p></li><li>'
							+'<label>车速：</label><p>'+item.unsafeSpeed+'(km/s)</p></li><li><label>转速：</label>'
							+'<p>'+item.unsafeRtteSpd+'转速(rpm)</p></li></ul></div>';
							var unsafeWindow = new AMap.InfoWindow({
								content: content,
								offset: new AMap.Pixel(16, -45)
							});
							unsafeWindow.open(map, [item.bLgt, item.bLtt]);
						});
						unsafeMarkers.push(unsafeMarker);
					}
					
					//超速
					if(item.sLgt){
						var overspeedMarker = new AMap.Marker({
					        map: map,
							position: [item.sLgt, item.sLtt]
					    });
						overspeedMarker.on('click', function(){
							content = '<div>车辆超速</div><ul><li>'
								+'<label>车辆：</label><p>'+item.lineName+'-'+item.licPltNo+'</p></li><li>'
								+'<label>超速发生时间：</label><p>'+item.spdingBeginTime+'</p></li><li><label>持续时长：</label>'
								+'<p>'+item.spdingCotnTime+'(秒)</p></li></div>';
							var overspeedWindow = new AMap.InfoWindow({
								content: content,
								offset: new AMap.Pixel(16, -45)
							});
							overspeedWindow.open(map, [item.sLgt, item.sLtt]);
						});
						overspeedMarkers.push(overspeedMarker);
					}
				});
			}
		});
	}

    /**
	 * 查询最近发生的报警列表
     */
    function getLastMiniteWarnList(){
        getAjaxData("/homeCaptain/getLastMiniteWarnList.htm", function(data){
			if(data){
				var faultTabCtx = "", bhvTabCtx = "", spdTabCtx = "";
				$.each(data, function(index, item){
					if(item.sign == 'FAULT'){
                        faultTabCtx += "<tr><td width='20%' class='al pl10'>" + item.licPltNo + "</td><td width='40%' class='al pl10'>" + item.warnType + "</td><td>" + item.rcrdTime + "</td></tr>";
					}else if(item.sign == 'BEHAVIOR'){
                        bhvTabCtx += "<tr><td width='20%' class='al pl10'>" + item.licPltNo + "</td><td width='40%' class='al pl10'>" + item.warnType + "</td><td>" + item.rcrdTime + "</td></tr>";
					}else{
                        spdTabCtx += "<tr><td width='20%' class='al pl10'>" + item.licPltNo + "</td><td width='40%' class='al pl10'>" + item.warnType + "</td><td>" + item.rcrdTime + "</td></tr>";
					}
				});
				$("#tab_faultType").html(faultTabCtx);
                $("#tab_unSafeBeh").html(bhvTabCtx);
                $("#tab_overSpd").html(spdTabCtx);
			}
        });
	}

	/**
     * 查询所选线路所在城市
     */
    function loadLineCity(lineId, lineName) {
        $.ajaxExt({
            url: "/homeSafe/getLoadLineCity.htm",
            data: {"funcType": "loadLineCity", "lineId": lineId, "className":"MapBaseDataVo"}
        }).done(function (data) {
        	var city = '', province = '';
            if (data && data.length > 0) {
            	city = data[0].city;
            	province = data[0].province;
            }
            lineSearch(city, lineName, province);
        });
    }
	
    /**
     * 公交线路查询
     * @param city 城市名称
     * @param lineName 线路名称
     */
    function lineSearch(city, lineName, province) {
    	var loct = city;
    	if(province == '北京'||province == '上海'||
         province == '天津'||province == '重庆'){
    		loct = province;
        }
    	
//         * 1. 首先调用公交路线查询服务(lineSearch)
//         * 2. 根据返回结果解析，输出解析结果(lineSearch_Callback)
//         * 3. 在地图上绘制公交线路()
         
        var linesearch = new AMap.LineSearch({
            pageIndex: 1,
            city: loct,
            pageSize: 2,
            extensions: 'all'
        });
        if(!linesearch){
        	map.setCity(city);
        }
        linesearch.search(lineName, function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
                lineSearch_Callback(result);
                var lineArr = result.lineInfo;
                var stationsLen = lineArr[0].via_stops.length;
                for (var i = 0; i < stationsLen; i++) {
                    stationMarkers.push(new AMap.Marker({
                        map: map,
                        position: lineArr[0].via_stops[i].location,
                        offset: new AMap.Pixel(-3, -3),
                        icon: $.getProjectName() + "/content/images/way_btn2.png",
                        title: lineArr[0].via_stops[i].name,
                        zIndex: 13
                    }));
                }
            }
            else{
            	map.setCity(city);
            }
        });
    }
	
    /**
	 * 公交路线查询服务返回数据解析概况
	 * @param data 线路数据集合（包括绘制线路的基点经纬度数据）
	 */
    function lineSearch_Callback(data) {
        var lineArr = data.lineInfo;
        var lineNum = data.lineInfo.length;
        if (lineNum == 0) {
        } else if(lineNum == 1){
        	for (var i = 0; i < lineNum; i++) {
                var pathArr = lineArr[i].path;
                var stops = lineArr[i].via_stops;
                var startPot = stops[0].location;
                var endPot = stops[stops.length - 1].location;
                if (i == 0)
                    drawbusLine(startPot, endPot, pathArr);
            }
        } else {
            for (var i = 0; i < lineNum-1; i++) {
                var pathArr = lineArr[i].path;
                var stops = lineArr[i].via_stops;
                var startPot = stops[0].location;
                var endPot = stops[stops.length - 1].location;
                if (i == 0)
                    drawbusLine(startPot, endPot, pathArr);
            }
        }
    }

    /**
	 * 绘制路线
	 * @param startPot 开始站点位置信息
	 * @param endPot 结束站点位置信息
	 * @param BusArr 公交线路基点经纬度集合
	 */
    function drawbusLine(startPot, endPot, BusArr) {
        //绘制起点，终点
        new AMap.Marker({
            map: map,
            position: [startPot.lng, startPot.lat], //基点位置
            icon: $.getProjectName() + "/content/images/start_flag.png",
            zIndex: 10
        });
        new AMap.Marker({
            map: map,
            position: [endPot.lng, endPot.lat], //基点位置
            icon: $.getProjectName() + "/content/images/end_flag.png",
            zIndex: 10
        });
        //绘制乘车的路线
        busPolyline = new AMap.Polyline({
            map: map,
            path: BusArr,
            strokeColor: "#09f",//线颜色
            strokeOpacity: 0.8,//线透明度
            strokeWeight: 6//线宽
        });
        map.setFitView();
    }

    //设置高度
    setHeight();
	//构建地图
    createMap();
});
$('.index2-table-wrap').on('mouseenter','td:not(.hover-none)',function(e){
	var index = $(this).nextAll().length;
	var $parent = $(this).closest('table');
	$('tr', $parent).each(function (i, tr) {
		var len = $('td', tr).length;
		if (len) {
			$('td:eq(' + (len - index - 1) + ')', tr).addClass('bg-f2f2f2');
		}
	});

}).on('mouseleave','td:not(.hover-none)',function(){
	var index = $(this).nextAll().length;
	var $parent = $(this).closest('table');
	$('tr', $parent).each(function (i, tr) {
		var len = $('td', tr).length;
		if (len) {
			$('td:eq(' + (len - index - 1) + ')', tr).removeClass('bg-f2f2f2');
		}
	});

});
